package com.sjb.cp.manager;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.sjb.cp.config.COSConfig;
import com.sjb.cp.exception.BusinessException;
import com.sjb.cp.exception.ErrorCode;
import com.sjb.cp.exception.ThrowUtils;
import com.sjb.cp.model.dto.file.UploadPictureResult;
import com.sun.corba.se.spi.ior.IdentifiableFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author:sjb
 * @CreateTime:2024-12-12
 * @Description: 通用文件管理
 * @Version：1.0
 */
@Component
@Slf4j
public class FileManager {

    @Resource
    private CosManager cosManager;

    @Resource
    private COSConfig cosConfig;

    /**
     * 上传图片
     * @param file
     * @param uploadPreFix
     * @return
/*     */
    @Deprecated
    public UploadPictureResult uploadPicture(MultipartFile file,String uploadPreFix) {
        validatePicture(file);

        // 图片上传地址
        String uuid = RandomUtil.randomString(16);
        String filename = file.getOriginalFilename();
        String uploadFileName = String.format("%s_%s.%s",DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(filename));

        // 上传路径
        String uploadPath = String.format("/%s/%s", uploadPreFix, uploadFileName);

        File tempFile = null;
        try {
            // 创建临时文件
            tempFile = File.createTempFile(uploadPreFix, null);
            file.transferTo(tempFile);

            // 上传图片
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, tempFile);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            int picHeight = imageInfo.getHeight();
            int picWidth = imageInfo.getWidth();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();

            // 封装返回结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setPicName(FileUtil.mainName(filename));
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            uploadPictureResult.setPicSize(FileUtil.size(tempFile));
            uploadPictureResult.setUrl(cosConfig.getHost() + "/" + uploadPath);
            return uploadPictureResult;
        } catch (IOException e) {
            log.error("图片上传到对象存储失败",e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        }finally {
            this.deleteTempFile(tempFile);
        }
    }

    /**
     * 校验文件
     * @param file
     */
    public void validatePicture(MultipartFile file) {
        ThrowUtils.throwIf(file == null, ErrorCode.PARAMS_ERROR,"文件不能为空");

        // 校验文件大小
        long size = file.getSize();
        final long ONE_M = 1024 * 1024L;
        ThrowUtils.throwIf(size > ONE_M * 2,ErrorCode.PARAMS_ERROR,"文件大小不能超过2M");

        // 校验文件后缀
        String suffix = FileUtil.getSuffix(file.getOriginalFilename());
        // 允许上传的文件后缀
        final List<String> ALLOWED_UPLOAD_PREFIX = Arrays.asList("jpg","jpeg","png","gif");
        ThrowUtils.throwIf(!ALLOWED_UPLOAD_PREFIX.contains(suffix),ErrorCode.PARAMS_ERROR,"文件类型错误");
    }


    /**
     * 删除文件
     * @param file
     */
    private void deleteTempFile(File file) {
        if (file == null){
            return;
        }
        boolean deleteResult = file.delete();
        if (!deleteResult){
            log.error("file delete error, filepath = {}", file.getAbsolutePath());
        }
    }


}
